package hotLeetcode;

import java.util.*;

public class H199Leetcode {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

//    public List<Integer> rightSideView(TreeNode root) {
//        List<Integer> listLeft = getLeft(root.left);
//        List<Integer> listRight = getLeft(root.right);
//        if (listRight.size() >= listLeft.size()) {
//            return listRight;
//        }
//        return null;
//    }
//
//    private List<Integer> getLeft(TreeNode root) {
//        List<Integer> result = new ArrayList<>();
//
//        while (root != null) {
//            result.add(root.val);
//            root = root.left;
//        }
//
//        return result;
//    }
//



    //层序遍历
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty() ) {
            List<Integer> list = new ArrayList<>();
            for (int i = queue.size(); i > 0 ; i--) {
                TreeNode poll = queue.poll();
                list.add(poll.val);
                if (poll.left != null) queue.offer(poll.left);
                if (poll.right != null) queue.offer(poll.right);

            }
            res.add(list.get(list.size() - 1));
        }

        return res;

    }




    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        treeNode.left = new TreeNode(2);
        treeNode.left.right = new TreeNode(5);
        treeNode.right = new TreeNode(3);
        treeNode.right.right = new TreeNode(4);

        H199Leetcode h199Leetcode = new H199Leetcode();
        System.out.println(h199Leetcode.rightSideView(treeNode));

    }


}
